<template>
  <div class="feat-report">
      <div class="top">
        <div class="filters">
          <div class="filter">
            <span>项目：</span>
            <el-select size="small" style="width: 150px;" v-model="queryParams.appid" @change="onAppchange">
              <el-option v-for="item in permission_projectList" :value="item.app_id" :label="item.name" :key="item.app_id"></el-option>
            </el-select>
          </div>
          <div class="filter">
            <span class="filter-item_label">版本：</span>
            <span class="filter-item_opts">
              <version-select ref="versionSelect" :selOptions="versionOpts" v-model="queryParams.version" @change="reRender"></version-select>
            </span>
          </div>
          <div class="filter">
            <span class="filter-item_label">渠道：</span>
            <span class="filter-item_opts">
              <select-check-box
                class="select-box"
                doubleColumn
                v-model="queryParams.unionid"
                :selOptions="channelOpts"
                checkAllLabel="全部渠道"
                filterable
                @change="reRender"
              />
            </span>
          </div>
          <div class="filter">
            <span class="filter-item_label">选择日期：</span>
            <span class="filter-item_opts">
              <date-range
                :dateRange.sync="queryParams.time_range"
                :dateType.sync="queryParams.time_grain_sqla"
                @change="reRender"
              />
            </span>
          </div>
        </div>
        <div
          class="filters"
          style="margin: 16px 0;"
        >
          <div class="filter">
            <span class="filter-item_label">图标筛选：</span>
            <span class="filter-item_opts">
              <el-cascader
                v-model="queryParams.indicator"
                :disabled="casDisabled"
                :options="chartOpts"
                :show-all-levels="false"
                :props="casProps"
                collapse-tags
                popper-class="chart-filter"
                @change="chartChange"
              ></el-cascader>
            </span>
          </div>
        </div>
      </div>

      <div class="charts um-scroll">
        <div
          class="chart-wrap"
          v-for="item in checkedList"
          :key="item.value"
        >
          <div class="title">{{ item.label }}</div>
          <!-- <div
            class="map list um-scroll"
            v-if="item.ranking"
          >
            <ul class="ranking">
              <li
                class="ranking_item"
                v-for="(t, i) in item.rankingList"
                :key="i"
              >
                <span class="order">{{ (i + 1) }}</span>
                <span class="label">{{ t.label }}</span>
                <span class="value">{{ fmtNumer(t.value) }}</span>
              </li>
            </ul>
          </div> -->
          <mix-chart
            class="map"
            :query="queryParams"
            :indic="item"
          />
        </div>
      </div>
  </div>
</template>

<script type="text/javascript">
import { mapGetters } from 'vuex'
import DateRange from './components/DateRange'
import { getVersionTree } from '@/api'
import { parseTime } from '@/utils/index'
import { getDashboardId, getAllStatEvents } from '@/api/feature/index'
import { getChannelByAppId } from '@/api/system/channel'
import MixChart from './components/MixChart'
import { DATE_TYPE } from './constant'
const dateFmt = '{y}-{m}-{d}'
const maxChk = 8
const datasource = process.env.NODE_ENV === 'production' ? 10 : 2
export default {
  name: 'FeatReport',
  components: {
    DateRange,
    MixChart
  },
  props: {},
  data () {
    const d = new Date()
    d.setDate(d.getDate() - 1)
    const end = parseTime(d, dateFmt)
    const start = parseTime(d.setDate(d.getDate() - 6), dateFmt)
    return {
      queryParams: {
        granularity: 'day_num',
        version: [],
        unionid: [],
        time_range: [start, end],
        time_grain_sqla: DATE_TYPE.DAY,
        indicator: [],
        appid: null,
        datasource
      },
      versionOpts: [],
      channelOpts: [],
      statEvents: [],
      casDisabled: false,
      casProps: {
        multiple: true,
        emitPath: false,
        expandTrigger: 'click'
      },
      checkedList: [],
      oldIndiList: [],
      chartOpts: []
    }
  },
  created () {
    if (this.permission_projectList.length) {
      this.queryParams.appid = this.permission_projectList[0].app_id
    }
    this.init()
  },
  methods: {
    async init () {
      const data = await getDashboardId({
        appid: this.queryParams.appid, page: 'feature'
      })
      getVersionTree({ app_id: this.queryParams.appid, is_test: false })
        .then(res => {
          let list = res.data || []
          this.versionOpts = list
        })

      getChannelByAppId({ app_id: this.queryParams.appid }).then(res => {
        this.channelOpts = res.data.list.map(t => ({
          value: t.channel_id,
          label: `${t.name} (${t.channel_id})`
        }))
      })

      getAllStatEvents(data?.id).then(res => {
        this.statEvents = res.data || []
        const defIndi = []
        this.chartOpts = this.statEvents.reduce((arr, item) => {
          const it = arr.find(t => t.label === item.module)
          const obj = {
            value: item.id,
            label: item.title,
            metrics: item.metrics || [],
            disabled: false
          }
          if (it) {
            it.children.push(obj)
          } else {
            arr.push({
              value: item.module,
              label: item.module,
              children: [obj],
              disabled: false
            })
          }
          return arr
        }, [])
        this.chartOpts.some(item => item.children.some(it => {
          if (defIndi.length < maxChk) {
            defIndi.push(it.value)
            return false
          } else {
            return true
          }
        }))
        const indis = Object.keys(this.chartOptMap)
        // 过滤掉不存在在的指标（fix 正式/测试环境id不一致）
        this.queryParams.indicator = this.queryParams.indicator.filter(val => indis.includes(String(val)))
        // 设置默认指标
        if (!this.queryParams.indicator.length) this.queryParams.indicator = defIndi
        this.chartChange(this.queryParams.indicator)
      })
    },
    onAppchange () {
      this.queryParams.version = []
      this.queryParams.unionid = []
      this.queryParams.indicator = []
      this.checkedList = []
      this.oldIndiList = []
      this.init()
    },
    reRender () {

    },
    chartChange (val) {
      if (val.length > maxChk) {
        const arr = this.oldIndiList.slice()
        const more = val.filter(v => !arr.includes(v))
        arr.push(...more.slice(0, maxChk - arr.length))
        this.queryParams.indicator = arr
      }
      const { indicator } = this.queryParams
      const over = indicator.length === maxChk
      this.chartOpts.forEach(item => {
        item.children.forEach(it => {
          it.disabled = over && !indicator.includes(it.value)
        })
        item.disabled = !item.children.some(t => !t.disabled)
      })
      if (this.oldIndiList.length !== indicator.length) {
        this.oldIndiList = indicator.slice()
        this.setCheckedList()
        this.reRender()
      }
    },
    setCheckedList () {
      this.checkedList = this.queryParams.indicator.slice().sort((a, b) => a - b).map(val => ({
        ...this.chartOptMap[val]
      }))
    }
  },
  computed: {
    ...mapGetters('zcsd-core', ['permission_projectList']),
    chartOptMap () {
      return this.chartOpts.reduce((obj, t) => {
        (t.children || []).forEach(m => (obj[m.value] = m))
        return obj
      }, {})
    }
  }
}
</script>

<style lang="scss" scoped>
.feat-report {
  .el-card ::v-deep .el-card__body {
    display: flex;
    flex-direction: column;
    overflow: hidden;
  }

  .filters {
    display: flex;
    flex-wrap: wrap;

    .filter {
      display: flex;
      margin-right: 20px;
      align-items: center;

      &:last-of-type {
        margin-right: 0;
      }

      .label {
        margin-right: 8px;
      }
    }
  }

  .charts {
    flex: 1;
    margin-left: -10px;
    margin-right: -10px;

    .chart-wrap {
      display: inline-flex;
      width: calc(50% - 20px);
      height: 450px;
      margin: 10px;
      padding: 12px;
      flex-direction: column;
      border: 1px solid rgba(0, 0, 0, .05);
      box-shadow: 2px 2px 4px 0 rgba(0, 0, 0, .3);

      .title {
        font-size: 20px;
      }

      .map {
        flex: 1;
      }

      .list {
        padding: 10px 100px;

        .ranking_item {
          display: flex;
          align-items: center;
          margin-top: 10px;

          &:nth-of-type(1) .order {
            color: #fff;
            background-color: #f59a23;
          }

          &:nth-of-type(2) .order {
            color: #fff;
            background-color: #aaa;
          }

          &:nth-of-type(3) .order {
            color: #fff;
            background-color: #c48f5b;
          }

          .order {
            flex: 24px 0 0;
            width: 24px;
            height: 24px;
            line-height: 24px;
            color: #333;
            text-align: center;
            border-radius: 50%;
            background-color: #ddd;
          }

          .label {
            flex: 1;
            padding: 0 20px;
            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;
          }
        }
      }
    }
  }

  .select-box {
    /deep/ .el-select__tags {

      .el-select__tags-text {
        display: inline-block;
        max-width: 70px;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
      }
      .el-tag__close {
        top: -7px;
      }
    }
  }
}
</style>
